# routes/statistics_routes.py
from flask import Blueprint, jsonify
from datetime import datetime
from services.statistic import get_basic_stats, get_defect_type_stats
from system.logger import Logger
from flask import request
from pathlib import Path
import os

statistics_bp = Blueprint('statistics', __name__, url_prefix='/api')
logger = Logger(root_dir=".", verbose_info=True, verbose_error=True)

@statistics_bp.route('/statistics', methods=['GET'])
def get_statistics():
    """获取实时统计数据"""
    try:
        # 获取最近 24 小时的统计数据
        time_range_spec = "latest_hours:24"
        basic_stats = get_basic_stats("logs/", time_range_spec)
        defect_stats = get_defect_type_stats("logs/", time_range_spec)

        # 提取基础统计
        basic = basic_stats.get("basic_stats", {})
        total_processed = basic.get("total", 0)
        total_normal = basic.get("passed", 0)
        total_defective = basic.get("defective", 0)
        pass_rate = basic.get("pass_rate", 0.0)

        # 提取缺陷类型统计
        defect_counts = {"crazing": 0, "inclusion": 0, "patches": 0, "pitted_surface": 0, "rolled_in_scale": 0, "scratches": 0}
        for defect in defect_stats.get("defect_type_stats", {}).get("defect_types", []):
            defect_type = defect.get("type", "").lower()
            if defect_type in defect_counts:
                defect_counts[defect_type] = defect.get("count", 0)

        stats = {
            "total_processed": total_processed,
            "total_normal": total_normal,
            "total_defective": total_defective,
            "pass_rate": pass_rate,
            "defect_counts": defect_counts,
            "last_update": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        logger.info(f"Statistics retrieved: {stats}")
        return jsonify(stats)
    except Exception as e:
        logger.error(f"Failed to get statistics: {str(e)}")
        return jsonify({}), 500

@statistics_bp.route('/statistics/detail', methods=['POST'])
def get_statistics_detail():
    """获取详细统计数据（时间序列）"""
    try:
        # 从 JSON 请求体中获取参数
        data = request.get_json(force=True)

        time_range_spec = data.get('time_range_spec', 'latest_hours:24')
        resample_freq = data.get('resample_freq', '1D')
        stats_type = data.get('type', 'basic')

        logger.info("请求详细统计数据",
                    time_range_spec=time_range_spec,
                    resample_freq=resample_freq,
                    stats_type=stats_type)

        if stats_type == 'defect_type':
            result = get_defect_type_stats("logs/", time_range_spec, resample_freq)
            detail_key = 'time_series_defect_types'
        else:
            result = get_basic_stats("logs/", time_range_spec, resample_freq)
            detail_key = 'time_series'

        response_data = {
            "metadata": result.get("metadata", {}),
            "details": result.get(detail_key, [])
        }

        return jsonify(response_data)
    except Exception as e:
        logger.error(f"获取详细统计数据失败: {str(e)}")
        return jsonify({"error": "Failed to retrieve detailed statistics"}), 500

    